//
//  MyOrderViewController.m
//  Edumap
//
//  Created by 辰领科技 on 16/7/18.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "MyOrderViewController.h"
#import "MyOrderTableViewCell.h"
#import "PayTypeViewController.h"
#import "OrderDetailsViewController.h"
#import "WriteCommentViewController.h"

static NSString *cellIdentifier = @"MyOrderTableViewCell";

@interface MyOrderViewController ()
<UITableViewDelegate,UITableViewDataSource>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIScrollView *scroview;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *allIndentButton;//全部
@property (weak, nonatomic) IBOutlet UIButton *waitPayButton;//我的家教
@property (weak, nonatomic) IBOutlet UIButton *waitCommentButton;//我的培训
@property(nonatomic,strong)NSMutableArray * indentsArray;
@property (weak, nonatomic) IBOutlet UILabel *noticeLabel;



@end

@implementation MyOrderViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView.header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _indentsArray = [NSMutableArray array];
    _pageNO = 1;
    [self initViewLayout];
    [self addRefreshing];
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroview];
    
    [_tableView registerNib:[UINib nibWithNibName:cellIdentifier bundle:nil] forCellReuseIdentifier:cellIdentifier];
    _tableView.dataSource = self;
    _tableView.delegate = self;
}

- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark == 切换订单
- (IBAction)changeIndentType:(UIButton *)sender {
    sender.selected = YES;
    _pageNO = 1;
    if (sender==_allIndentButton) {     //全部
        _waitPayButton.selected = NO;
        _waitCommentButton.selected = NO;
    }else if(sender == _waitPayButton){ //我的家教
        _allIndentButton.selected = NO;
        _waitCommentButton.selected = NO;

    }else{                               //我的培训
        _waitPayButton.selected = NO;
        _allIndentButton.selected = NO;

    }
    [_tableView.header beginRefreshing];
}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self MyOrder];
        });
    }];
    [self.tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.indentsArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self MyOrder];
        });
    }
    
}


#pragma mark - 获取订单数据
- (void)MyOrder {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"memberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:[NSNumber numberWithInteger:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInteger:PageSize] forKey:@"pageSize"];
    
    self.shareApi.delegate=self;
    if (_allIndentButton.selected) {     //全部
        [self.shareApi  requestOperationWithDic:dic withPath:JY_mallOrderList withHttpType:@"POST" withTag:JY_JY_mallOrderList];
    }else if(_waitPayButton.selected){ //我的家教
         [self.shareApi  requestOperationWithDic:dic withPath:JY_myMallLectureOrderList withHttpType:@"POST" withTag:JY_JY_myMallLectureOrderList];
    }else{                               //我的培训
        [self.shareApi  requestOperationWithDic:dic withPath:JY_myMallOrderList withHttpType:@"POST" withTag:JY_JY_myMallOrderList];
    }
   
}

#pragma mark - <UITableViewDelegate&&UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
       return _indentsArray.count;
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 132*VerticalRatio();
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyOrderTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell= [[MyOrderTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
    }
    NSDictionary * dic = _indentsArray[indexPath.row];
    NSString * status =@"";
    if (_allIndentButton.selected) {
        status = [NSString stringWithFormat:@"%@",dic[@"status"]];
      
        cell.titleLabel.text = [NSString stringWithFormat:@"%@",dic[@"name"]];
        cell.detailLabel.text = [NSString stringWithFormat:@"%@",dic[@"content"]];
        cell.moneyLabel.text = [NSString stringWithFormat:@"￥%.2f",[dic[@"price"]floatValue]];
        
        NSString * image = [NSString stringWithFormat:@"%@",dic[@"image"]];
        if (image.length>0) {
            [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
    }else if (_waitPayButton.selected){
        status = [NSString stringWithFormat:@"%@",dic[@"mlorStatus"]];
      
        NSString * image = [NSString stringWithFormat:@"%@",dic[@"mallExpert"][@"mexpImage"]];
        if (image.length>0) {
            [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
        cell.titleLabel.text = [NSString stringWithFormat:@"%@",dic[@"mallExpert"][@"mexpName"]];
        cell.detailLabel.text = [NSString stringWithFormat:@"%@",dic[@"mallExpert"][@"mexpContent"]];
        cell.moneyLabel.text = [NSString stringWithFormat:@"￥%.2f",[dic[@"mallExpert"][@"mexpPrice"]floatValue]];
    }else{
          status = [NSString stringWithFormat:@"%@",dic[@"status"]];
        NSString * image = [NSString stringWithFormat:@"%@",dic[@"image"]];
        if (image.length>0) {
            [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
        cell.titleLabel.text = [NSString stringWithFormat:@"%@",dic[@"name"]];
        cell.detailLabel.text = [NSString stringWithFormat:@"%@",dic[@"content"]];
        cell.moneyLabel.text = [NSString stringWithFormat:@"￥%.2f",[dic[@"price"]floatValue]];
    }
    
    if ([status isEqualToString:@"1"]) {
        [cell.cellButton setTitle:@"立即支付" forState:UIControlStateNormal];
    } else if ([status isEqualToString:@"2"]) {
        [cell.cellButton setTitle:@"评论" forState:UIControlStateNormal];
    } else if ([status isEqualToString:@"3"]) {
        [cell.cellButton setTitle:@"已评论" forState:UIControlStateNormal];
    } else if ([status isEqualToString:@"4"]) {
        [cell.cellButton setTitle:@"已取消" forState:UIControlStateNormal];
    } else if ([status isEqualToString:@"5"]) {
        [cell.cellButton setTitle:@"已删除" forState:UIControlStateNormal];
    }

    
    
    
    cell.payBlock= ^(){
        NSString * status = @"";
        NSString * payId = @"";
        NSString * payOrderPrice = @"";
        NSString * payOrderName = @"";
        NSString * payOrderNo = @"";
        NSString * classid = @"";
        if (_allIndentButton.selected) {
            status = [NSString stringWithFormat:@"%@",dic[@"status"]];
            payId =[NSString stringWithFormat:@"%@",dic[@"orderId"]] ;
            payOrderPrice =[NSString stringWithFormat:@"%@",dic[@"price"]] ;
            payOrderName = [NSString stringWithFormat:@"%@",dic[@"name"]];
            payOrderNo =[NSString stringWithFormat:@"%@",dic[@"orderNo"]];
            classid = [NSString stringWithFormat:@"%@",dic[@"id"]];
        }else if (_waitPayButton.selected){
            status = [NSString stringWithFormat:@"%@",dic[@"mlorStatus"]];
            payId = [NSString stringWithFormat:@"%@",dic[@"mlorId"]];
            payOrderPrice = [NSString stringWithFormat:@"%@",dic[@"mlorPrice"]] ;
            payOrderName = [NSString stringWithFormat:@"%@",dic[@"mallExpert"][@"mexpName"]] ;
            payOrderNo =[NSString stringWithFormat:@"%@",dic[@"mlorNo"]];
            classid = [NSString stringWithFormat:@"%@",dic[@"mexpId"]];

        }else{
            status = [NSString stringWithFormat:@"%@",dic[@"status"]];
            payId =[NSString stringWithFormat:@"%@",dic[@"orderId"]] ;
            payOrderPrice =[NSString stringWithFormat:@"%@",dic[@"price"]] ;
            payOrderName = [NSString stringWithFormat:@"%@",dic[@"name"]];
            payOrderNo =[NSString stringWithFormat:@"%@",dic[@"orderNo"]];
            classid = [NSString stringWithFormat:@"%@",dic[@"id"]];

        }
        if ([status isEqualToString:@"1"]) {
            UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeTeachStoryboard" bundle:nil];
            PayTypeViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"PayType"];
            page.payId = payId;
            page.payOrderName = payOrderName;
            page.payOrderPrice = payOrderPrice;
            page.payOrderNo = payOrderNo;
            [[Common getNavigation]pushViewController:page];

        }else if ([status isEqualToString:@"2"]){
            UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"PersonalStoryboard" bundle:nil];
            WriteCommentViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"WriteComment"];
            page.indentId = payId;
            page.classId = classid;
            if (_allIndentButton.selected) {
                NSString *Str = [NSString stringWithFormat:@"%@",_indentsArray[indexPath.row][@"type"]];
                if ([Str isEqualToString:@"1"]) {
                    page.type = @"1";
                   
                } else if ([Str isEqualToString:@"2"]) {
                    page.type = @"2";
                }
                page.image = [NSString stringWithFormat:@"%@",dic[@"image"]];
            } else if (_waitPayButton.selected) {
                page.type = @"1";
                page.image = [NSString stringWithFormat:@"%@",dic[@"mallExpert"][@"mexpImage"]];
            } else if (_waitCommentButton.selected) {
                page.type = @"2";
                page.image = [NSString stringWithFormat:@"%@",dic[@"image"]];
            }
            [[Common getNavigation]pushViewController:page];
        }
    };

    
   
    return cell;
}

//定义 UITableView cell 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UIStoryboard *secondStroyBoard = [UIStoryboard storyboardWithName:@"PersonalStoryboard" bundle:nil];
    OrderDetailsViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"OrderDetails"];
    if (_allIndentButton.selected) {
        
        NSString *Str = [NSString stringWithFormat:@"%@",_indentsArray[indexPath.row][@"type"]];
        if ([Str isEqualToString:@"1"]) {
            page.ChooseInterface = @"1";
            page.mlorId = [NSString stringWithFormat:@"%@",_indentsArray[indexPath.row][@"orderId"]];
            page.classId = [NSString stringWithFormat:@"%@",_indentsArray[indexPath.row][@"mexpId"]];
        } else if ([Str isEqualToString:@"2"]) {
            page.ChooseInterface = @"2";
            page.mordId = [NSString stringWithFormat:@"%@",_indentsArray[indexPath.row][@"orderId"]];
            page.classId = [NSString stringWithFormat:@"%@",_indentsArray[indexPath.row][@"id"]];
        }
        
    } else if (_waitPayButton.selected) {
        
        page.ChooseInterface = @"1";
        page.mlorId = [NSString stringWithFormat:@"%@",_indentsArray[indexPath.row][@"mlorId"]];
         page.classId = [NSString stringWithFormat:@"%@",_indentsArray[indexPath.row][@"mexpId"]];
    } else if (_waitCommentButton.selected) {
        
        page.ChooseInterface = @"2";
        page.mordId = [NSString stringWithFormat:@"%@",_indentsArray[indexPath.row][@"orderId"]];
         page.classId = [NSString stringWithFormat:@"%@",_indentsArray[indexPath.row][@"id"]];
    }
    [[Common getNavigation]pushViewController:page];
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag==JY_JY_mallOrderList || tag == JY_JY_myMallLectureOrderList || tag == JY_JY_myMallOrderList) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.indentsArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.indentsArray addObject:entity];
                }
                if (_indentsArray.count == 0) {
                    _noticeLabel.hidden = NO;
                }else{
                    _noticeLabel.hidden = YES;
                }
                [_tableView reloadData];
                
            });
            
        }
    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    [self dismissWaitDialog];
}


@end
